package com.jzo2o.orders.manager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.foundations.ServeApi;
import com.jzo2o.api.foundations.dto.response.ServeAggregationResDTO;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.response.AvailableCouponsResDTO;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 下单服务类
 * </p>
 *
 * @author itcast
 * @since 2023-07-10
 */
@Slf4j
@Service
public class OrdersCreateServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersCreateService {

    @Override
    public List<Orders> queryoverTimepageOrderlistBycount(Integer count) {
        //根据订单创建时间查询超过15分钟未支付的订单
        List<Orders> list = lambdaQuery()
                .eq(Orders::getOrdersStatus, OrderStatusEnum.NO_PAY.getStatus())
                //小于当前时间减去15分钟,即待支付状态已过15分钟
                .lt(Orders::getCreateTime, LocalDateTime.now().minusMinutes(15))
                .last("limit" + count)
                .list();
        return list;
    }

    @Resource
    ServeApi serveApi;

    @Resource
    CouponApi couponApi;
    @Override
    public List<AvailableCouponsResDTO> getAvailableCoupons(Long serveId, Long purNum) {
        //1.校验服务是否存在
        ServeAggregationResDTO serve = serveApi.findById(serveId);
        if (ObjectUtil.isEmpty(serve) || serve.getSaleStatus() != 2) {
            throw new BadRequestException("服务不可用");
        }
        //2. 计算订单总金额
        BigDecimal totalAmount = serve.getPrice().multiply(new BigDecimal(purNum));

        //3.通过openFeign调用 获取可用优惠卷列表
        List<AvailableCouponsResDTO> dtoList = couponApi.getAvailable(totalAmount);
        //4.返回
        return dtoList;

    }
}
